﻿using Newtonsoft.Json;
using SmarterCharger.Library.Infrastructure;
using SmarterCharger.Library.Model;
using SmarterCharger.Library.Repositories.Interfaces;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace SmarterCharger.Library.Repositories
{
    internal class EnergyDeviceRepository : IEnergyDeviceRepository
    {
        private const string GetEnergyDevicesUrl = "https://s-api.fifthplay.com/Web/api/Energy/GetEnergyDevices";

        public async Task<HttpResponseResult<IEnumerable<EnergyDevice>>> GetEnergyDevices(string username, string password)
        {
            if (string.IsNullOrWhiteSpace(username)) throw new ArgumentNullException("username");
            if (string.IsNullOrWhiteSpace(password)) throw new ArgumentNullException("password");

            using (var httpClient = new BasicAuthenticationHttpClient(username, password))
            {
                var request = await httpClient.GetAsync(GetEnergyDevicesUrl);
                var result = new HttpResponseResult<IEnumerable<EnergyDevice>> { StatusCode = request.StatusCode };
                
                if (!request.IsSuccessStatusCode)
                    return result;

                var content = await request.Content.ReadAsStringAsync();
                var energyDevices = JsonConvert.DeserializeObject<IEnumerable<EnergyDevice>>(content);

                return new HttpResponseResult<IEnumerable<EnergyDevice>>
                {
                    StatusCode = request.StatusCode,
                    Result = energyDevices
                };
            }
        }
    }
}
